package com.itstyle.seckill.web;

import com.itstyle.seckill.common.entity.Result;
import com.itstyle.seckill.service.ISeckillDistributedService;
import com.itstyle.seckill.service.SeckillVsService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 几种方式并发性能比较
 * startDBPCC_ONE   1200/s
 * startRedisLock	650/s
 * redisBuffLock	1700/s
 * redisBuffDecr    2000/s
 * atomic           2000/s
 */
@RestController
@RequestMapping("seckillVS")
public class SeckillVSController {

    @Autowired
    private ISeckillDistributedService seckillDistributedService;
    @Autowired
    private SeckillVsService seckillVsService;

    /**
     * 初始化某个秒杀的库存
     * @param seckillId
     * @return
     */
    @PostMapping("/init")
    @Transactional
    public Result init(long seckillId){
        Result result = seckillVsService.init(seckillId);
        return result;
    }


    /**
     * 综合
     *atomic + redis.decr
     * 		每台机器atomic库存过滤掉一部分，剩下的redis中心库存
     */
    @PostMapping("/atomicRedisBuffDecr")
    @Transactional
    public Result atomicRedisBuffDecr(long seckillId){
        Result result = seckillVsService.atomicRedisBuffDecr(seckillId);
        return result;
    }


    /**
     *
     * atomic
     * 单机（因为库存配在本服务上）
     *
     *  2000/s
     */
    @PostMapping("/atomic")
    @Transactional
    public Result atomic(long seckillId){
        Result result = seckillVsService.atomic(seckillId);
        return result;
    }

    /**
     *
     * 用redis库存 + decr代替redisson的作用
     *
     *  2000/s
     */
    @PostMapping("/redisBuffDecr")
    @Transactional
    public Result redisBuffDecr(long seckillId){
        Result result = seckillVsService.redisBuffDecr(seckillId);
        return result;
    }


    /**
     * redis库存 + redisson
     *
     * 1700/s
     */
    @PostMapping("/redisBuffLock")
    @Transactional
    public Result redisBuffLock(long seckillId){
        Result result = seckillVsService.redisBuffLock(seckillId);
        return result;
    }

    /**
     * redisson
     * 650/s		比悲观锁效率低
     * @param seckillId
     * @return
     */
    @ApiOperation(value="秒杀一(Rediss分布式锁)",nickname="科帮网")
    @PostMapping("/startRedisLock")
    public Result startRedisLock(long seckillId){
        Result result = seckillVsService.startSeckilRedisLock(seckillId, 0);
        return result;
    }

    @PostMapping("/startDBPCC_ONE")
    public Result startDBPCC_ONE(long seckillId){
        Result result = seckillVsService.startSeckilDBPCC_ONE(seckillId, 0);
        return result;
    }
}
